package cn.bigcontainer.alt.sys.service.impl;

import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.sys.dto.SysDistrictDto;
import cn.bigcontainer.alt.sys.po.SysDistrict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import cn.bigcontainer.alt.sys.mapper.SysDistrictMapper;

import cn.bigcontainer.alt.sys.service.SysDistrictService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 行政区域的Service接口实现类.
 *
 * @author jiaod
 * @date 2021-06-15
 */
@Service
@Transactional
public class SysDistrictServiceImpl implements SysDistrictService {

	@Resource
	private SysDistrictMapper sysDistrictMapper;

	@Override
	public List<List<SysDistrictDto>> getProvinceCityDistricts(String province, String city) {
		if (WoKit.isEmpty(province)) {
			province = "11";
			// city = "01";
		}
		List<SysDistrict> provinces = sysDistrictMapper.selectList(new QueryWrapper<SysDistrict>().eq("city", "0"));
		List<SysDistrictDto> provinceDtos = new ArrayList<>();
		for (SysDistrict p : provinces) {
			SysDistrictDto pDto = new SysDistrictDto(p);
			if (pDto.getProvince().equals(province)) {
				pDto.setSelected(true);
			}
			provinceDtos.add(pDto);
		}
		List<SysDistrict> cities = getCities(province);
		List<SysDistrictDto> cityDtos = new ArrayList<>();
		for (SysDistrict c : cities) {
			SysDistrictDto cDto = new SysDistrictDto(c);
			if (cDto.getCity().equals(city)) {
				cDto.setSelected(true);
			}
			cityDtos.add(cDto);
		}
		return Arrays.asList(provinceDtos, cityDtos);
	}

	private List<SysDistrict> getCities(String province) {
		List<SysDistrict> cities = sysDistrictMapper.selectList(new QueryWrapper<SysDistrict>().eq("province", province).ne("city", "0").eq("area", "0"));
		return cities;
	}

	@Override
	public List<SysDistrictDto> getCityDistricts(String province) {
		List<SysDistrict> cities = getCities(province);
		return WoKit.getDtos(SysDistrictDto.class, cities);
	}

	@Override
	public String getProvinceCityName(String province, String city) {
		SysDistrict provinceDistrict = sysDistrictMapper.selectOne(new QueryWrapper<SysDistrict>().eq("province", province).eq("city", "0"));
		SysDistrict cityDistrict = sysDistrictMapper.selectOne(new QueryWrapper<SysDistrict>().eq("province", province).eq("city", city).eq("area", "0"));
		return provinceDistrict.getName() + "," + cityDistrict.getName();
	}
}
